package stz.flash.option;

import net.rim.device.api.ui.Field;
import net.rim.device.api.ui.FieldChangeListener;
import net.rim.device.api.ui.Keypad;
import stz.flash.string.OptionString;
import blackberry.util.field.DjChoiceField;
import blackberry.util.field.DjLabelField;

abstract public class AbstractGlobalKeyChoiceField extends DjChoiceField implements FieldChangeListener{

	public static final int INT_NONE = -1;
	
	protected Option option = Option.getIns();

	public AbstractGlobalKeyChoiceField(String item, String info) {
		super(DjLabelField.createSimpleLabel(item), 
				OptionLabel.createInfoLabel(info),
				null);
		
		setChoices(getChoices());
		setSelectedIndex(convertKeyToString());
		setChangeListener(this);
	}
	
	private String convertKeyToString() {
		
		if (getKey() == Keypad.KEY_SPEAKERPHONE) 
			return OptionString.MUTE_KEY;
		
		else if (getKey() == Keypad.KEY_VOLUME_UP) 
			return OptionString.VOLUME_UP_KEY;
		
		else if (getKey() == Keypad.KEY_VOLUME_DOWN) 
			return OptionString.VOLUME_DOWN_KEY;
		
		else if (getKey() == Keypad.KEY_END) 
			return OptionString.END_KEY;
		
		else if (getKey() == Keypad.KEY_BACKWARD) 
			return OptionString.BACKWARD_KEY;
		
		else if (getKey() == Keypad.KEY_FORWARD) 
			return OptionString.FORWARD_KEY;
		
		else if (getKey() == INT_NONE)
			return OptionString.NONE;
		
		return null;
	}
	
	public void fieldChanged(Field field, int i) {
		
		if (i == PROGRAMMATIC || i == 0) 
			return;
		
		setKeyFromSelected(getChoice(getSelectedIndex()));
	}
	
	protected void setKeyFromSelected(Object selectedName) {
		
		if (((String)selectedName).equals(OptionString.MUTE_KEY)) 
			setKey(Keypad.KEY_SPEAKERPHONE);
		
		else if (selectedName.equals(OptionString.VOLUME_UP_KEY)) 
			setKey(Keypad.KEY_VOLUME_UP);
		
		else if (((String)selectedName).equals(OptionString.VOLUME_DOWN_KEY)) 
			setKey(Keypad.KEY_VOLUME_DOWN);
		
		else if (((String)selectedName).equals(OptionString.END_KEY)) 
			setKey(Keypad.KEY_END);
		
		else if (((String)selectedName).equals(OptionString.BACKWARD_KEY)) 
			setKey(Keypad.KEY_BACKWARD);
		
		else if (((String)selectedName).equals(OptionString.FORWARD_KEY)) 
			setKey(Keypad.KEY_FORWARD);
	
		else if (((String)selectedName).equals(OptionString.NONE)) 
			setKey(INT_NONE);
		
	}
	
	abstract protected String[] getChoices();
	abstract protected int getKey();
	abstract protected void setKey(int key);
}
